// 假设的 HKBabyBluetoothManager 扫描规则
// 在 HKBabyBluetoothManager 中，常见的设备过滤规则包括：

// 通过设备名称前缀过滤。
// 通过服务 UUID 过滤。
// 通过 RSSI 信号强度过滤。
// 支持多条件组合过滤。

import 'dart:async';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter/foundation.dart';

class BluetoothManager {
  static final BluetoothManager _instance = BluetoothManager._internal();
  factory BluetoothManager() => _instance;
  //BluetoothManager._internal();
  BluetoothManager._internal() {
    // _listenBluetoothState(); // 监听蓝牙状态
  }

  /// 获取单例实例
  static BluetoothManager get instance => _instance;

  StreamSubscription? _scanSubscription;
  final List<ScanResult> _scanResults = [];
  BluetoothDevice? _connectedDevice;
  final Map<Guid, BluetoothCharacteristic> _characteristics = {};

  final ValueNotifier<List<ScanResult>> scanResultsNotifier = ValueNotifier([]);
  final ValueNotifier<bool> isScanningNotifier = ValueNotifier(false);

  final ValueNotifier<BluetoothAdapterState> bluetoothStateNotifier =
      ValueNotifier(BluetoothAdapterState.unknown); // 监听蓝牙状态

  ////////////属性
  // 设置查找规则是名称前缀过滤(默认不过滤,全部展示)
  String perName = "";

  // 外设的服务UUID值
  String serverUUIDString = "";

  // 外设的写入UUID值
  String writeUUIDString = "";

  // 外设的读取UUID值
  String readUUIDString = "";

  // 是否手机开启蓝牙
  bool openBluState = false;

  // 是否连接到设备
  bool isConnect = false;

  /// 监听蓝牙状态
  void _listenBluetoothState() {
    FlutterBluePlus.adapterState.listen((state) {
      bluetoothStateNotifier.value = state;
      openBluState = (state == BluetoothAdapterState.on);

      if (state == BluetoothAdapterState.on) {
        debugPrint('蓝牙已开启');
      } else {
        debugPrint('蓝牙未开启');
      }
    });

/*
如何使用
在 Flutter 界面监听蓝牙状态：

ValueListenableBuilder<BluetoothState>(
  valueListenable: BluetoothManager.instance.bluetoothStateNotifier,
  builder: (context, state, child) {
    return Text(state == BluetoothState.on ? "蓝牙已开启" : "蓝牙未开启");
  },
);
这样，你的 BluetoothManager 就可以自动监听蓝牙状态，并在 UI 中实时更新状态。
*/
  }

  /// 开始扫描设备
  Future<void> startScan({String? deviceNamePrefix}) async {
    // 停止之前的扫描
    await stopScan();

    _scanResults.clear();
    scanResultsNotifier.value = List.unmodifiable(_scanResults);

    isScanningNotifier.value = true;
    await FlutterBluePlus.startScan(timeout: const Duration(seconds: 10));
    _scanSubscription = FlutterBluePlus.scanResults.listen((results) {
      //////////////////////////////
      //设置查找规则是名称g名称前缀过滤
      if (perName.isEmpty) return;
      //#为分隔符
      List<String> array =
          perName.split(',').map((item) => item.trim()).toList();
      // array = ['YYLX', 'ZZYM', 'BF_MM', 'ZNYM','ZNMM',];

      for (ScanResult result in results) {
        print("Device Name: ${result.advertisementData.advName}");
        String peripheralName = result.advertisementData.advName;

        bool containsDevice1 = false;

        for (String element in array) {
          if (element == peripheralName) {
            containsDevice1 = true;
            break;
          }
        }
        //表示这个设备符合条件，允许发现。
        if (containsDevice1) {

          
        }

        //print(containsDevice1); // 输出：true
      }

      //////////////////////////////
      _scanResults.clear();
      print("------------results:$results");
      for (var result in results) {
        if (deviceNamePrefix == null ||
            result.device.platformName.startsWith(deviceNamePrefix)) {
          // 避免重复添加
          if (!_scanResults
              .any((r) => r.device.remoteId == result.device.remoteId)) {
            _scanResults.add(result);
          }
        }
      }
      scanResultsNotifier.value = List.unmodifiable(_scanResults);
    });
  }

  /// 停止扫描
  Future<void> stopScan() async {
    isScanningNotifier.value = false;
    await _scanSubscription?.cancel();
    _scanSubscription = null;
    await FlutterBluePlus.stopScan();
  }

  /// 获取扫描结果
  List<ScanResult> getScanResults() => List.unmodifiable(_scanResults);

  /// 连接设备  BluetoothDevice(对应服务特性 CBPeripheral *peripheral)
  Future<void> connectDevice(BluetoothDevice device) async {
    try {
      await stopScan(); // 确保扫描已停止
      _connectedDevice = device;
      await device.connect();
      await _discoverServices(device);

      // 监听设备断开连接
      _connectedDevice?.connectionState.listen((state) {
        if (state == BluetoothConnectionState.disconnected) {
          _handleDisconnectedDevice();
        }
      });
    } catch (e) {
      debugPrint("连接设备失败: $e");
      rethrow;
    }
  }

  /// 断开设备
  Future<void> disconnectDevice() async {
    try {
      await _connectedDevice?.disconnect();
    } catch (e) {
      debugPrint("断开设备失败: $e");
    } finally {
      _handleDisconnectedDevice();
    }
  }

  /// 发现服务和特征值
  Future<void> _discoverServices(BluetoothDevice device) async {
    final services = await device.discoverServices();
    for (var service in services) {
      for (var characteristic in service.characteristics) {
        _characteristics[characteristic.uuid] = characteristic;
      }
    }
  }

  /// 写入数据
  Future<void> writeCharacteristic(Guid uuid, List<int> value) async {
    final characteristic = _characteristics[uuid];
    if (characteristic != null) {
      try {
        await characteristic.write(value, withoutResponse: false);
      } catch (e) {
        debugPrint("写入特征值失败: $e");
        rethrow;
      }
    } else {
      throw Exception("特征值 $uuid 不存在");
    }
  }

  /// 读取数据
  Future<List<int>?> readCharacteristic(Guid uuid) async {
    final characteristic = _characteristics[uuid];
    if (characteristic != null) {
      try {
        return await characteristic.read();
      } catch (e) {
        debugPrint("读取特征值失败: $e");
        return null;
      }
    }
    return null;
  }

  /// 处理设备断开连接
  void _handleDisconnectedDevice() {
    debugPrint("设备已断开连接");
    _connectedDevice = null;
    _characteristics.clear();
  }

  /// 销毁管理器时释放资源
  Future<void> dispose() async {
    await stopScan();
    await disconnectDevice();
    scanResultsNotifier.dispose();
    isScanningNotifier.dispose();
  }
}
